package com.scuec.groupfive.Controller;

import com.scuec.groupfive.dto.PastExamSubmissionDTO;
import com.scuec.groupfive.entity.PastExam;
import com.scuec.groupfive.service.PastExamRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/past-exams")
@CrossOrigin
public class PastExamRecordController {

    @Autowired
    private PastExamRecordService pastExamRecordService;

    @GetMapping("/user/{userId}")
    public List<PastExam> getByUserId(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        return pastExamRecordService.getPastExamRecordsByUserId(userId, page, size);
    }

    @GetMapping("/search")
    public List<PastExam> search(
            @RequestParam Long userId,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate,
            @RequestParam(required = false) String keyword,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size
    ) {
        return pastExamRecordService.searchPastExamRecords(
                userId, startDate, endDate, keyword, page, size
        );
    }

    @PostMapping("/submit")
    public ResponseEntity<Map<String, Object>> submitPastExam(
            @RequestBody PastExamSubmissionDTO submission,
            @RequestHeader("userId") Long userId
    ) {
        try {
            Long recordId = pastExamRecordService.submitPastExam(
                    userId,
                    submission.getExamType(),
                    submission.getExamYear(),
                    submission.getQuestions()
            );

            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "提交成功");

            Map<String, Object> data = new HashMap<>();
            data.put("recordId", recordId);
            response.put("data", data);

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "提交失败: " + e.getMessage());

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    @GetMapping("/detail/{recordId}")
    public Map<String, Object> getPastExamRecordDetail(@PathVariable Long recordId) {
        try {
            return pastExamRecordService.getPastExamRecordDetail(recordId);
        } catch (Exception e) {
            throw new ResponseStatusException(
                    HttpStatus.INTERNAL_SERVER_ERROR,
                    "获取考试详情失败: " + e.getMessage()
            );
        }
    }
    // PastExamRecordController.java
// 在类中添加：
    @PostMapping("/favorite")
    public ResponseEntity<?> toggleFavorite(
            @RequestBody Map<String, Object> requestBody) {
        try {
            Long questionId = Long.valueOf(requestBody.get("questionId").toString());
            Boolean isFavorite = Boolean.valueOf(requestBody.get("isFavorite").toString());
            Long userId = Long.valueOf(requestBody.get("userId").toString());

            pastExamRecordService.toggleFavorite(userId, questionId, isFavorite);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "操作失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }
}